<?php

namespace App\Services;

use App\Models\SpecificationAttribute;
use Illuminate\Support\Facades\Cache;

class SpecificationService
{
    /**
     * 获取所有启用的规格属性
     */
    public function getActiveAttributes()
    {
        return Cache::remember('specification_attributes', 3600, function () {
            return SpecificationAttribute::active()
                ->ordered()
                ->get()
                ->keyBy('key');
        });
    }

    /**
     * 处理产品规格
     */
    public function processProductSpecifications($product)
    {
        if (!$product->variants || $product->variants->isEmpty()) {
            return [];
        }

        // 从变体中提取规格选项
        $specs = $this->extractSpecificationsFromVariants($product->variants);
        
        // 获取产品的变体属性（优先）
        $variantAttributes = $product->variantAttributes()
            ->get()
            ->keyBy('slug');
        
        // 获取规格属性定义（作为后备）
        $specAttributes = $this->getActiveAttributes();

        // 转换为前端需要的格式
        return $this->formatSpecificationsForFrontend($specs, $variantAttributes, $specAttributes);
    }

    /**
     * 从变体中提取规格选项
     */
    private function extractSpecificationsFromVariants($variants)
    {
        $specs = [];
        
        foreach ($variants as $variant) {
            if ($variant->attributes) {
                foreach ($variant->attributes as $key => $value) {
                    if (!isset($specs[$key])) {
                        $specs[$key] = [];
                    }
                    if (!in_array($value, $specs[$key])) {
                        $specs[$key][] = $value;
                    }
                }
            }
        }

        return $specs;
    }

    /**
     * 格式化规格数据供前端使用
     */
    private function formatSpecificationsForFrontend($specs, $variantAttributes, $specAttributes)
    {
        $result = [];
        
        foreach ($specs as $key => $options) {
            // 优先使用产品的变体属性，其次使用全局规格属性
            $attribute = $variantAttributes->get($key) ?? $specAttributes->get($key);
            
            // 将简单字符串数组转换为对象数组
            $formattedOptions = array_map(function($option) {
                return [
                    'name' => $option,
                    'value' => $option
                ];
            }, $options);
            
            $result[] = [
                'key' => $key,
                'name' => $attribute ? $attribute->name : $key,
                'type' => $attribute ? $attribute->type : 'select',
                'is_required' => $attribute ? $attribute->is_required : false,
                'options' => $formattedOptions,
                'attribute_options' => $attribute ? $attribute->options : null
            ];
        }

        return $result;
    }

    /**
     * 根据规格查找变体
     */
    public function findVariantBySpecs($product, $selectedSpecs)
    {
        if (!$product->variants) {
            return null;
        }

        return $product->variants->first(function ($variant) use ($selectedSpecs) {
            if (!$variant->attributes) {
                return false;
            }
            
            return collect($selectedSpecs)->every(function ($value, $key) use ($variant) {
                return $variant->attributes[$key] === $value;
            });
        });
    }


    /**
     * 清除规格属性缓存
     */
    public function clearCache()
    {
        Cache::forget('specification_attributes');
    }
}
